package com.zhenzhang.myblog.controller;

import com.zhenzhang.myblog.annotations.Authentication;
import com.zhenzhang.myblog.dao.UserDao;
import com.zhenzhang.myblog.entity.role.User;
import com.zhenzhang.myblog.entity.role.UserRole;
import com.zhenzhang.myblog.exception.JsonException;
import com.zhenzhang.myblog.service.UserService;
import com.zhenzhang.myblog.utils.AssetsManager;
import com.zhenzhang.myblog.utils.CookieUtil;
import com.zhenzhang.myblog.utils.FileUtils;
import com.zhenzhang.myblog.utils.JsonResult;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.http.HttpResponse;
import java.util.UUID;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Resource
    private UserDao userDao;
    @Resource
    private UserService userService;


    @GetMapping("session")
    public void login(User user, HttpSession session){
        var u = userService.validUser(user.getUsername(), user.getPassword());
        session.setAttribute("loginUser", u);
    }

    @PostMapping("password")
    public void modifyPassword(@RequestBody User user, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser != null) {
            if (!loginUser.getId().equals(user.getId()) && !loginUser.getAdmin()) {
                throw new JsonException(403,"用户权限不足");
            }
            userDao.updateUserPassword(user);
        }else {
            throw new JsonException(403,"用户权限不足");
        }
    }

    @GetMapping("username")
    public String getUsernameById(Integer aid){
        return userDao.getUsernameById(aid);
    }

    @GetMapping({"info", "info/{username}"})
    @Authentication(role = {UserRole.USER,UserRole.ADMIN})
    public User getUserInfo(@PathVariable(required = false) String username, HttpSession session){
        if(username == null){
            User loginUser = (User) session.getAttribute("loginUser");
            loginUser.setPassword(null); //为了安全
            return loginUser;
        }else {
            User otherUser = userDao.findUserByUsername(username);
            otherUser.setPassword(null);
            return otherUser;
        }
    }

    // Post表示推送/提交资源，用来增加数据，这里注册用户其实就是增加一个用户，所以就用post
    @PostMapping
    public void register(@RequestBody User user) {
        userService.addUser(user);
    }

    @PutMapping
    @Authentication(role = {UserRole.USER,UserRole.ADMIN})
    public void update(@RequestBody User user, @SessionAttribute User loginUser){
        user.setId(loginUser.getId());// 只修改已登录的用户的信息
        System.out.println(user);
        userDao.updateUser(user);
    }

    @DeleteMapping("session")
    @Authentication(role = {UserRole.USER,UserRole.ADMIN})
    public void logout(HttpSession session){
        session.removeAttribute("loginUser");
    }

    @PostMapping("avatar")
    @Authentication(role = {UserRole.USER,UserRole.ADMIN})
    public JsonResult uploadAvatar(@RequestBody MultipartFile file,HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        String username = loginUser.getUsername();
        userService.setAvatar(username,file);
        return JsonResult.getInstance();
    }

    //若{username}为空则获取已经登录用户的头像 不为空则根据username字段获取头像
    @GetMapping({"avatar/{username}", "avatar"})
    public HttpEntity<org.springframework.core.io.Resource> getAvatar(@PathVariable(required = false) String username,
                                                                      HttpSession session,
                                                                      HttpServletResponse response)
            throws IOException {
        if (username == null) {
            User user = (User)(session.getAttribute("loginUser"));
            if (user == null) {
                // return 响应默认头像 游客请求空用户名
                response.sendRedirect("/api/assets/defaultAvatar.jpg");
                return null;
            }
            username = user.getUsername();
        }
        UrlResource resource = userService.getUserAvatarResource(username);
        if (resource == null) {
            // return 响应默认头像 头像不存在
            response.sendRedirect("/api/assets/defaultAvatar.jpg");
            return null;
        }
        // return 响应正常头像
        return FileUtils.getFileResponseEntity(resource);
    }

}

